import { getUserInfo, getUserDetail, login } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: null,
    timeStamp: '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      state.timeStamp = Date.now()
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    async loginAction(context, payload) {
      const res = await login(payload)
      context.commit('setToken', res)
    },
    async getUserInfo(context) {
      const res = await getUserInfo() // 获取基本资料
      const detail = await getUserDetail(res.userId) // 获取详细信息
      // 将两个接口返回的数据合并，一块存到 userInfo中
      const userInfo = { ...res, ...detail }
      // console.log(res)
      context.commit('setUserInfo', userInfo)
      return res
    },
    logout(context) {
      context.commit('setToken', null)
      context.commit('setUserInfo', {})
      // 清除路由规则，在子模块中调用另一个子模块中的 mutations 方法
      context.commit('permission/setRoutes', [], { root: true })
    }
  }
}
